package com.ustc.hewei.consumerweb.controller;


import cn.hutool.core.bean.BeanUtil;
import com.ustc.hewei.commonmodule.dto.LoginFormDTO;
import com.ustc.hewei.commonmodule.dto.Result;
import com.ustc.hewei.commonmodule.dto.UserDTO;
import com.ustc.hewei.commonmodule.entity.User;
import com.ustc.hewei.commonmodule.entity.UserInfo;
import com.ustc.hewei.commonmodule.service.IUserInfoService;
import com.ustc.hewei.commonmodule.service.IUserService;
import com.ustc.hewei.consumerweb.utils.UserHolder;
import com.ustc.hewei.nettyrpc2_0.common.annotation.AutowireService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hewei
 * @since 2022-10-05
 */
@RestController
@RequestMapping("/user")
public class UserController {
    public IUserService getUserService() {
        return userService;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    public IUserInfoService getUserInfoService() {
        return userInfoService;
    }

    public void setUserInfoService(IUserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }

    @Resource
    private IUserService userService;

    @Resource
    private IUserInfoService userInfoService;

    @PostMapping("code")
    public Result sendCode(@RequestParam("phone") String phone, HttpSession session) {
        return userService.sendCode(phone);
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginFormDTO loginForm, HttpSession session){
        return userService.login(loginForm);
    }

    @PostMapping("/logout")
    public Result logout(){
        return userService.logout(UserHolder.getUser());
    }

    @GetMapping("/me")
    public Result me(){
        UserDTO user = UserHolder.getUser();
        return Result.ok(user);
    }

    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long userId){
        // 查询详情
        UserInfo info = userInfoService.getById(userId);
        if (info == null) {
            // 没有详情，应该是第一次查看详情
            return Result.ok();
        }
        info.setCreate_time(null);
        info.setUpdate_time(null);
        // 返回
        return Result.ok(info);
    }

    @GetMapping("/{id}")
    public Result queryUserById(@PathVariable("id") Long userId){
        // 查询详情
        User user = userService.getById(userId);
        if (user == null) {
            return Result.ok();
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        // 返回
        return Result.ok(userDTO);
    }
}

